package com.lw.server;

import com.lw.common.Message;
import com.lw.common.MessageType;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Date;
import java.util.List;
import java.util.Scanner;

/**
 * 服务端广播消息
 */
public class SendNewsToAllService implements Runnable {

    private Scanner scanner = new Scanner(System.in);

    @Override
    public void run() {
        while (true) {//为了多次推送消息，如果有界面的话，是不需要while死循环的

            String news = scanner.nextLine();//等待输入时会阻塞线程

            if(news.equals("exit")){//退出推送服务
                break;
            }

            Message message = new Message();
            message.setSender("服务器");
            message.setContent(news);
            message.setSendTime(new Date().toString());
            message.setMsgType(MessageType.MESSAGE_TO_ALL_MES);

            System.out.println("广播信息");

            //获取所有在线用户，群发消息
            List<ServerConnectClientThread> allClientConnectServerThread = ManageClientThread.getAllClientConnectServerThread();
            for (ServerConnectClientThread serverConnectClientThread : allClientConnectServerThread) {
                Socket socket = serverConnectClientThread.getSocket();
                try {
                    ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
                    outputStream.writeObject(message);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
